library(tidyverse)
library(redist)
library(scales)

source("R/00_custom_functions.R")

plans_orig <- read_rds("data/SC/sim/HD_ms-parallel/plans_orig.rds")
plans_da04 <- read_rds("data/SC/sim/HD_ms-parallel/plans_da04.rds")
plans_da12 <- read_rds("data/SC/sim/HD_ms-parallel/plans_da12.rds")
map_sc <- read_rds("data/SC/sim/HD_ms-parallel/redist_map_orig.rds")

calc_grp_pct = function(pl, type="partisan", map = map_sc) {
    if (type == "partisan")
        pl = mutate(pl, grp = group_frac(map, gov_vest_DEM, gov_vest_DEM + gov_vest_REP))
    else
        pl = mutate(pl, grp = group_frac(map, vap_orig - vap_white_orig, vap_orig))

    pl %>%
        number_by(grp) %>%
        as_tibble()
}

dem_pcts = bind_rows(orig = calc_grp_pct(plans_orig, "partisan"),
                     da12 = calc_grp_pct(plans_da12, "partisan"),
                     .id = "source")

plot_grp_norm = function(pcts, xlab, quantiles = 10) {
    pcts %>%
        mutate(dist_qtl = santoku::chop_deciles(district)) %>%
        # mutate(ref_grp = grp[draw == "<init> 1" & source == "orig"]) %>%
        group_by(dist_qtl) %>%
        ggplot(aes(x = as.factor(dist_qtl), y = grp, fill = lbl_source(source))) +
        geom_hline(yintercept = 0.5,
                   lty = "dashed",
                   color = "#444444") +
        ggthemes::geom_tufteboxplot(aes(color = lbl_source(source))) +
        # geom_boxplot(outlier.size = 0.1) +
        scale_fill_manual(values = PAL_DAS) +
        scale_color_manual(values = PAL_DAS) +
        scale_y_continuous("Difference from enacted plan",
                           labels = percent) +
        labs(x = xlab, fill = "Plans\nsampled from") +
        theme_ppmf() +
        guides(color = FALSE) +
        theme(axis.text = element_text(angle = 90),
              panel.grid.major.x = element_blank())
}

samp <- dem_pcts %>% filter(!str_detect(draw, "init")) %>% sample_frac(0.01)
plot_grp_norm(samp,
              "Districts, ordered by Democratic two-party vote share")



